package cn.lopr.im.android.db.service;

import android.util.Log;

import org.greenrobot.greendao.query.WhereCondition;

import java.util.Date;
import java.util.List;

import cn.lopr.im.android.db.entity.HomeDialogue;
import cn.lopr.im.android.db.entity.Message;
import cn.lopr.im.android.db.gen.MessageDao;
import cn.lopr.im.android.db.helper.CommonDaoUtils;
import cn.lopr.im.android.db.helper.DaoUtilsStore;
import cn.lopr.im.android.mvp.view.activities.MainActivity;

/**
 * @author shuangyang7
 * @date 2021/1/4 12:00
 */
public class HomeDialogueDaoService {
    static CommonDaoUtils<Message> messageDao = DaoUtilsStore.getInstance().getMessageDaoUtils();
    static CommonDaoUtils<HomeDialogue> homeDialogueDao = DaoUtilsStore.getInstance().getHomeDialogueUtils();

    public static void initHomeDialogue() {
        List<Message> messages = messageDao.queryByQueryBuilder(new WhereCondition.StringCondition("1 GROUP BY " +
                MessageDao.Properties.FromUser.columnName));
        Log.i("Message", "initHomeDialogue: " + messages);
        for (Message message : messages) {
            HomeDialogue _homeDialogue = new HomeDialogue();
            _homeDialogue.setIsDelete(0);
            _homeDialogue.setToUser(message.getFromUser());
            homeDialogueDao.insert(_homeDialogue);
        }
        Log.i("Message", "initHomeDialogue: " + homeDialogueDao.queryAll());
    }

    public static void setIsDelete(String toUser, int isDelete) {
        List<HomeDialogue> homeDialogues = homeDialogueDao.queryByNativeSql("where to_User=? and from_user=?",
                new String[]{toUser, MainActivity.user.getPhone()});
        if (homeDialogues.size() != 0) {
            HomeDialogue homeDialogue = homeDialogues.get(0);
            homeDialogue.setIsDelete(isDelete);
            homeDialogue.setLastUpdate(new Date());
            homeDialogueDao.update(homeDialogue);

        } else {
            HomeDialogue homeDialogue = new HomeDialogue();
            homeDialogue.setToUser(toUser);
            homeDialogue.setFromUser(MainActivity.user.getPhone());
            homeDialogue.setIsDelete(isDelete);
            homeDialogue.setLastUpdate(new Date());
            homeDialogueDao.insert(homeDialogue);

        }
    }

}
